1// This is the helper function using the original Voronoi script
 2// licensed under the terms of the GNU GPL version 3 (or later)
 3
 4use <voronoi.scad>
 5
 6//
 7// The voronoi_polygon() function fills an arbitrary polygon with a Voronoi pattern.
 8//
 9// Parameters:
10//   border (required) ... polygon to be filled by a Voronoi pattern (array of [x, y] pairs, no holes)
11//   n                 ... number of nuclei sites to be generated (pattern density; complexity: O(n^2) )
12//   thickness         ... the thickness of the lines between cells
13//   round             ... the radius applied to corners (fillet in CAD terms)
14//   edging            ... the width of the border, set 0 for no border
15//   seed              ... seed for the random generator (random if undefined)
16//
17module voronoi_polygon(border, n=30, thickness=1.7, round=1.0, edging=3.0, seed=undef) {
18
19    // bounding box
20    only_x = [ for (point = border) point[0] ];
21    only_y = [ for (point = border) point[1] ];
22    min_x = min(only_x);
23    min_y = min(only_y);
24    max_x = max(only_x);
25    max_y = max(only_y);
26    // echo([[min_x,min_y],[max_x,max_y]]);
27
28    // compute sizes, centers and scaling
29    size_x = max_x - min_x;
30    size_y = max_y - min_y;
31    L = max(size_x, size_y);
32    scale_voro = [ size_x / L, size_y / L ];
33    center_poly = [(min_x + max_x) / 2, (min_y + max_y) / 2];
34
35    // subtract Voronoi pattern from the border polygon
36    difference() {
37        polygon(border);
38        translate(center_poly) scale(scale_voro)
39            random_voronoi(n = n, nuclei = false, L = L, thickness = thickness,
40                  round = round, min = 0, max = L, seed = seed, center = true);
41    }
42
43    // add the border edge if required
44    if (edging) {
45        difference() {
46            polygon(border);
47            offset(delta = -edging) polygon(border);
48        }
49    }
50}
51
52//
53// Examples
54// (render more times to see random effects)
55//
56
57// a complex red shape far from the coordinates origin
58border1 = [[362.13, 35.7], [388.01, 47.59], [409.81, 58.66], [427.16, 68.73],
59           [439.78, 77.62], [447.43, 85.19], [450.0, 91.29], [447.43, 95.84],
60           [439.78, 98.75], [427.16, 99.96], [409.81, 99.47], [388.01, 97.27],
61           [362.13, 93.41], [350.0, 60.5]];
62color([1,0,0]) linear_extrude(height = 1)
63    voronoi_polygon(border1);
64
65// negative blue box with no edging and some settings
66border2 = [[0,0], [-20,0], [-20,-20], [0,-20]];
67color([0,0,1]) linear_extrude(height = 2)
68    voronoi_polygon(border2, thickness=0.2, round=0.5, edging=0, seed=42);
69
70// longer green shape
71border3=[[0,8],[20,178],[40,178],[60,8]];
72color([0,1,0]) linear_extrude(height = 10)
73    voronoi_polygon(border3, n=50);